package structural.flyweight;


import java.util.HashMap;
import java.util.Map;

/**
 * 享元模式
 * 共享对象
 */

interface Product{
    public void action();
}

class Car implements Product{

    private String name;
    private String value;

    public Car(String name) {
        this.name = name;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public void action() {
        System.out.println("action----->"+this.name);
    }

    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", value='" + value + '\'' +
                '}';
    }
}


class ProductFactory{
    private static final Map<String,Product> productMap = new HashMap<>();

    public static Product getProduct(String name){
        Product product = productMap.get(name);
        if (product == null){
            product = new Car(name);
            productMap.put(name,product);
        }
        return product;
    }
}


class Test{
    public static void main(String[] args) {
        Product product = ProductFactory.getProduct("本田");
        System.out.println(product);
        Product product01 = ProductFactory.getProduct("本田");
        System.out.println(product01);
        Product product02 = ProductFactory.getProduct("雪佛兰");
        System.out.println(product02);

        System.out.println(product == product01);
        System.out.println(product == product02);


        ((Car)product).setValue("20");
        System.out.println(product);
        System.out.println(product01);
        System.out.println(product == product01);
    }
}